package com.cai.servlet.item;

import com.cai.dao.GoodsDao;
import com.cai.dao.impl.GoodsDaoImpl;
import com.cai.entity.Items;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Map;

/**
 * @author RuoLi
 */
@WebServlet(name = "ServletItemInsert", value = "/itemInsert")
public class ServletItemInsert extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        Map<String, String[]> map = request.getParameterMap();
        //添加器材
        Items item = new Items();
        //封装数据
        item.setItem_name(map.get("item_name")[0]);
        item.setItem_type(map.get("item_type")[0]);
        item.setItem_num(Integer.parseInt(map.get("item_num")[0]));
        item.setItem_log(map.get("item_log")[0]);
        GoodsDao goodsDao = new GoodsDaoImpl();
        //如果物品存在，不添加更改数据
        int status = goodsDao.selectTargetGoods(map.get("item_name")[0]);
        if (status != 1) {
            //如果不物品存在，添加数据
            int code = goodsDao.insertGoods(item);
            if (code != 0) {
                //添加成功
                request.getRequestDispatcher("/pageItems?page=1").forward(request, response);
            } else {
                //添加失败
                request.setAttribute("errorLog", "添加失败");
            }
        } else {
            //物品存在编辑数据
            int code = goodsDao.updateGoods(item);
            if (code!=0){
                //更新成功
                request.getRequestDispatcher("/pageItems?page=1").forward(request, response);
            }else {
                //更新失败
                request.setAttribute("errorLog", "更新失败");
            }
        }

    }
}
